/*
 * BGSubstraction.cpp
 *
 *  Created on: April 17, 2010
 *      Author: Víctor Gaspar
 *				Enrique López-Mañas
 *				Patricia Mateos Romero
 *
 *  NOTES: Todos los comentarios los dejo para que
 *  se pueda probar a posteriori paso a paso
 */

#include <cv.h>
#include <cvaux.h>
#include <highgui.h>
#include <stdio.h>
#include <sstream>
#include <sys/stat.h>

std::string BGPATH;
std::string LSTPATH;
std::string FMPATH;

bool FileExists(std::string strFilename) {
  struct stat stFileInfo;
  bool blnReturn;
  int intStat;

  // Attempt to get the file attributes
  intStat = stat(strFilename.c_str(),&stFileInfo);
  if(intStat == 0)
    blnReturn = true;
  else
    blnReturn = false;

  return(blnReturn);
}

// Foreground and Background extraction
int main(int argc, char* argv[]) {

	if(argc > 4)
	{
		printf("Too many arguments supplied.\n");
		exit(0);
	} else if (argc < 4){
		printf("Too few arguments supplied.\n");
		exit(0);
	}

	BGPATH = argv[1];
	LSTPATH = argv[2];
	FMPATH = argv[3];

	IplImage* bg_image = cvLoadImage(BGPATH.c_str());
	IplImage* bg_image_smooth = cvCreateImage(cvSize(bg_image->width,bg_image->height), 8, 3);
	IplImage* bg_image_hsl = cvCreateImage(cvSize(bg_image->width,bg_image->height), 8, 3);

	if (!bg_image) {
		printf("bad image \n");
		exit(0);
	}

	cvSmooth(bg_image, bg_image_smooth, CV_GAUSSIAN, 5, 5);
	cvCvtColor(bg_image_smooth, bg_image_hsl, CV_RGB2Luv);

	//cvNamedWindow("BG", 1);
	cvNamedWindow("FG", 1);
	//cvNamedWindow("IMG", 1);

	//create BG model
	CvBGStatModel* bg_model = cvCreateGaussianBGModel(bg_image_hsl);

	if(FileExists(LSTPATH))
	{
		IplImage* lst_image = cvLoadImage(LSTPATH.c_str());
		IplImage* lst_image_smooth = cvCreateImage(cvSize(lst_image->width,bg_image->height), 8, 3);
		IplImage* lst_image_hsl = cvCreateImage(cvSize(lst_image->width,lst_image->height), 8, 3);

		cvSmooth(lst_image, lst_image_smooth, CV_GAUSSIAN, 5, 5);
		cvCvtColor(lst_image_smooth, lst_image_hsl, CV_RGB2Luv);

		// Update model
		cvUpdateBGStatModel(lst_image_hsl, bg_model);

		// show images
		//cvShowImage("BG", bg_model->background);
		cvShowImage("FG", bg_model->foreground);
		//cvShowImage("IMG", lst_image_hsl);

		cvWaitKey();

		cvReleaseImage(&lst_image_hsl);
		cvReleaseImage(&lst_image_smooth);
		cvReleaseImage(&lst_image);
	}

	cvSaveImage("/home/victor/Development/traffiCVision/fg_sample.jpg", bg_model->foreground);

	cvReleaseImage(&bg_image_hsl);
	cvReleaseImage(&bg_image_smooth);
	cvReleaseImage(&bg_image);
	cvReleaseBGStatModel(&bg_model);

	return 0;
}

